import { Component, OnInit, Output, EventEmitter, Renderer2, AfterViewInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { LayoutMenuService } from './layout-menu.service';

@Component({
  moduleId: module.id,
  selector: 'app-layout-menu',
  templateUrl: './layout-menu.component.html',
  styleUrls: ['./layout-menu.component.scss'],
  host: {
    '(click)': 'menuClick()'
  }
})
export class LayoutMenuComponent implements OnInit, AfterViewInit {
  active: string = 'home';
  current: string;
  contentsExpandStatus: boolean = false;

  private windowWidth:number;
  private menuClicked:boolean;

  @Output() collapsed: EventEmitter<boolean> = new EventEmitter();

  constructor(private renderer:Renderer2, public layoutMenuService:LayoutMenuService) {}

  ngOnInit() {
    this.layoutMenuService.documentId.subscribe(id => {
      if (id) {
        this.active = 'document';
      }
    });
  }

  ngAfterViewInit () {
    this.collapsed.emit(this.contentsExpandStatus && this.active !== 'home');
    this.windowWidth = window.innerWidth;
    this.renderer.listen('window', 'resize', (event) => {
      this.windowWidth = window.innerWidth;
    });
    this.renderer.listen('document', 'click', (event) => {
      if (this.menuClicked) {
        this.menuClicked = false;
        return;
      }
      // 768, 992
      if (this.windowWidth < 992) {
        this.changeContentsStatus(false);
        this.collapsed.emit(false);
      }
    });
  }

  toggleContent (type: string) {
    if (this.active === type) {
      this.changeContentsStatus(!this.contentsExpandStatus);
    } else {
      this.changeContentsStatus(true);
    }
    this.active = type;
    this.collapsed.emit(this.contentsExpandStatus && this.active !== 'home');
  }

  changeContentsStatus (flag: boolean=false) {
    this.contentsExpandStatus = flag;
  }

  menuClick () {
    this.menuClicked = true;
  }
}
